package com.lsl.controller;

import com.lsl.entity.User;
import com.lsl.dto.UserDTO;
import com.lsl.entity.Result;
import com.lsl.service.UserService;

import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user-service")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/findUser/id/{id}")
    public Result<User> findUserById(@PathVariable Integer id) {
        User user = userService.getById(id);
        if (user == null) {
            return Result.error(404, "用户不存在");
        }
        return Result.success(user);
    }

    @GetMapping("/findUser/name/{username}")
    public Result<User> findUserByUsername(@PathVariable String username) {
        User user = userService.lambdaQuery()
                .eq(User::getUsername, username)
                .one();
        if (user == null) {
            return Result.error(404, "用户不存在");
        }
        return Result.success(user);
    }

    @PostMapping("/editUser")
    public Result<User> editUser(@RequestBody User user) {
        if (user.getId() == null) {
            return Result.error(400, "用户 ID 为空，请检查登录状态");
        }
        // 检查新用户名是否已存在
        User oldUser = userService.lambdaQuery()
                .eq(User::getUsername, user.getUsername())
                .ne(User::getId, user.getId())
                .one();
        if (oldUser != null) {
            return Result.error(401, "该用户名已被占用");   
        }
        // 检查新手机号码是否已存在
        User oldPhoneUser = userService.lambdaQuery()
                .eq(User::getPhone, user.getPhone())
                .ne(User::getId, user.getId())
                .one();
        if (oldPhoneUser != null) {
            return Result.error(401, "该手机号码已被注册"); 
        }
        // 更新用户信息
        boolean success = userService.updateById(user);
        if (!success) {
            return Result.error(500, "未知错误");
        }
        return Result.success(user);
    }

    @DeleteMapping("/deleteAccount/{id}")
    public Result<User> deleteAccount(@PathVariable Integer id) {
        boolean success = userService.removeById(id);
        if (!success) {
            return Result.error(500, "未知错误");
        }
        return Result.success(null);
    }

    @GetMapping("/findUser/ids/{ids}")
    public List<User> getUsersByIds(@PathVariable List<Integer> ids) {
        return userService.getUsersByIds(ids);
    }
}
